/**
 * 
 */
package com.softwareinlife.xmpp.server.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * This XMPP bot JID is xmppsoftwareinlife@appspot.com
 * 
 * @author jangsunjin@softwareinlife.com
 * 
 */
@SuppressWarnings("serial")
public class XMPPUnsubscribeServlet extends HttpServlet {

	/**
	 * Logger
	 */
	public static final Logger log = Logger.getLogger(XMPPUnsubscribeServlet.class
			.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.log(Level.ALL, this.getClass().getName() + " is start!");
		
		try {
			String strStatus = "";
			//STEP 1
			XMPPService xmpp = XMPPServiceFactory.getXMPPService();
			
			// STEP 2
			Message msg = xmpp.parseMessage(req);
			JID fromJid = msg.getFromJid();
			String body = msg.getBody();
			log.info("Received a message from " + fromJid + " and body = "
					+ body);
			// STEP 3
			String msgBody = "Software in Life: " + body;
			Message replyMessage = new MessageBuilder()
					.withRecipientJids(fromJid).withBody(msgBody).build();
			// STEP 4
			boolean messageSent = false;
			if (xmpp.getPresence(fromJid).isAvailable()) {
				SendResponse status = xmpp.sendMessage(replyMessage);
				messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
			}
			// STEP 5
			if (messageSent) {
				strStatus = "Message has been sent successfully";
			} else {
				strStatus = "Message could not be sent";
			}
			log.info(strStatus);
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}
}
